﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Chess.Common.Network;

namespace Chess.Server
{
    public class Session
    {
        private TcpClient _client { get; set; }
        private StreamReader _reader { get; set; }
        private StreamWriter _writer { get; set; }
        private Thread _worker { get; set; }
        private SerializedNetworkReader _serializedReader { get; set; }
        private SerializedNetworkWriter _serializedWriter { get; set; }
        private IPEndPoint _endPoint { get; set; }

        public Session(TcpClient client)
        {
            _client = client;
            _reader = new StreamReader(_client.GetStream());
            _writer = new StreamWriter(_reader.BaseStream);
            _worker = new Thread(NetworkLoop);
            _serializedReader = new SerializedNetworkReader(_reader);
            _serializedWriter = new SerializedNetworkWriter(_writer);

            _worker.Start();
        }

        public void Write(NetworkData data)
        {
            _serializedWriter.Write(data);
        }

        private void NetworkLoop()
        {
            while (true)
            {
                NetworkData data = _serializedReader.Read();
                Handler.Handle(this, data);
            }
        }
    }
}
